import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, message, Modal, Row} from "antd";
import type {Result} from "@/types/result";
import workExperienceApi from "@/api/workExperienceApi.ts";
import {WorkExperience} from "@/types/resp/workExperience";
import EmployeeSelector from "@/pages/employee/EmployeeSelector.tsx";

interface WorkExperienceAddProps {
  visible: boolean;
  id: number;
  onCloseWorkExperienceAdd: () => void;
}

const WorkExperienceAdd: React.FC<WorkExperienceAddProps> = ({visible, id, onCloseWorkExperienceAdd}) => {

  const [form] = Form.useForm<WorkExperience>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    employeeName: [
      { required: true, message: '请输入员工姓名' }
    ],
    company: [
      { required: true, message: '请输入公司名称' }
    ],
    position: [
      { required: true, message: '请输入岗位' }
    ],
  };

  let workExperienceForm: Partial<WorkExperience> = {}

  const [title, setTitle] = useState('新增工作经历');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑工作经历')
      initWorkExperienceFormById(id)
    } else {
      setTitle('新增工作经历')
      form.resetFields();
    }
  }, [visible]);

  const initWorkExperienceFormById = async (id: number) => {
    const resp: Result<WorkExperience> = await workExperienceApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      workExperienceForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let workExperience2Save:WorkExperience = form.getFieldsValue()
      if (id) {
        workExperience2Save = Object.assign(workExperienceForm, workExperience2Save)
      }
      const resp: Result<void> = await workExperienceApi.save(workExperience2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增工作经历')
    form.resetFields();
  };
  
  const [employeeSelectorVisible, setEmployeeSelectorVisible] = useState(false);
  const findEmployee = () => {
    setEmployeeSelectorVisible(true);
  }
  const handleEmployeeSelected = (selectedEmployee: { employeeId?: number; employeeName?: string; }) => {
    setEmployeeSelectorVisible(false)
    if (selectedEmployee && 'employeeId' in selectedEmployee) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      employeeId: selectedEmployee['employeeId'],
      employeeName: selectedEmployee['employeeName'],
      }));
    }
  };
  const handleCloseEmployeeSelector = () => {
    setEmployeeSelectorVisible(false)
  };

  const onBack = () => {
    onCloseWorkExperienceAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseWorkExperienceAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="workExperienceForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="employeeName" label="员工姓名"  rules={rules.employeeName}>
              <Input.Search placeholder="请选择员工姓名" onSearch={findEmployee} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="company" label="公司名称" rules={rules.company}>
              <Input maxLength={255} placeholder="请输入公司名称"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="position" label="岗位" rules={rules.position}>
              <Input maxLength={255} placeholder="请输入岗位"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="startDate" label="开始日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="endDate" label="结束日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={22}>
            <Form.Item name="responsibilities" label="岗位职责" labelCol={{span: 3}}>
              <Input.TextArea maxLength={65535} placeholder="请输入岗位职责" autoSize={{ minRows: 3, maxRows: 3 }}/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EmployeeSelector visible={employeeSelectorVisible} onEmployeeSelected={handleEmployeeSelected} onCloseEmployeeSelector={handleCloseEmployeeSelector} />
    </Modal>
  )
}

export default WorkExperienceAdd;
